package com.zainaer.activity;

import android.location.Location;
import android.os.Bundle;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.GeoPoint;
import com.baidu.mapapi.LocationListener;
import com.baidu.mapapi.MKLocationManager;
import com.baidu.mapapi.MapActivity;
import com.baidu.mapapi.MapView;
import com.baidu.mapapi.MyLocationOverlay;
import com.zainaer.R;

public class MapViewActivity extends MapActivity {

	private static final String KEY = "1B4AD432F28F78FBA1CAA586505FDB549192037F";
	private MapView view = null;
	private BMapManager manager = null;
	private MyLocationOverlay location = null;
	
	private LocationListener listener = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.map_tab);

		manager = new BMapManager(getApplication());
		manager.init(KEY, null);
		super.initMapActivity(manager);
		view = (MapView) findViewById(R.id.bmapsView);
		view.setBuiltInZoomControls(true);
		view.setDrawOverlayWhenZooming(true);
		
		MKLocationManager locationManager = manager.getLocationManager();
		locationManager.enableProvider(MKLocationManager.MK_NETWORK_PROVIDER);
		locationManager.enableProvider(MKLocationManager.MK_GPS_PROVIDER);
		location = new MyLocationOverlay(this, view);
		view.getOverlays().add(location);
		
		listener = new LocationListener() {
			
			@Override
			public void onLocationChanged(Location mylocation) {
				if(mylocation==null)
					return;
				GeoPoint pt = new GeoPoint((int)(mylocation.getLatitude()*1e6),
						(int)(mylocation.getLongitude()*1e6));
				view.getController().animateTo(pt);
			}
		};
	}

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	@Override
	protected void onDestroy() {
		if (manager != null) {
			manager.destroy();
			manager = null;
		}
		super.onDestroy();
	}

	@Override
	protected void onPause() {
		if (manager != null) {
			manager.getLocationManager().removeUpdates(listener);
			location.disableCompass();
			location.disableMyLocation();
			manager.stop();
		}
		super.onPause();
	}

	@Override
	protected void onResume() {
		if (manager != null) {
			location.enableMyLocation();
			location.enableCompass();
			manager.getLocationManager().requestLocationUpdates(listener);
			manager.start();
		}
		super.onResume();
	}

}